﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using XLZF.MicroServices.Common.Mapping;
using XLZF.MicroServices.IRepository;
using XLZF.MicroServices.Repository;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
#region Autofac

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    builder.RegisterType<UserRepository>().As<IUserRepository>();  // 直接注册某一个类和接口,左边的是实现类，右边的As是接口
});

#endregion

#region 响应 Ids4

builder.Services.AddAuthentication("Bearer")//Scheme:就是指定读信息的方式Bearer
    .AddJwtBearer("Bearer", option =>
    {
        option.Authority = "https://localhost:4000";//ids4的地址--专门获取公钥
        option.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            ValidateAudience = false
        };
        option.RequireHttpsMetadata = false;//false 就不验证https了
    });

builder.Services.AddAuthorization(option =>
{
    option.AddPolicy("Apiscope", builder =>
    {
        builder.RequireAuthenticatedUser();
        builder.RequireClaim("scope", "scope1");
    });
});

#endregion

#region Swagger

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "XLZF.Core", Version = "v1", Description = "E衣橱接口" });

    var file = Path.Combine(AppContext.BaseDirectory, "XLZF.MicroServices.Users.xml");//XML绝对路径

    var path = Path.Combine(AppContext.BaseDirectory, file); // xml⽂档绝对路径

    c.IncludeXmlComments(path, true);//true 显示控制器层注释

    c.OrderActionsBy(o => o.RelativePath);//对action的名称进行排序，如果有多个，就可以 看到效果了。
});

#endregion

#region AutoMapper

builder.Services.AddAutoMapper(typeof(AutoMapperConfigs));

#endregion

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication(); //鉴权 读取用户凭据

app.UseAuthorization();//授权  根据凭据查看有没有相关的权限

app.MapControllers().RequireAuthorization("Apiscope");//这是一个数组，可以多个，全局  必须通过 Apiscope 作用域才能授权访问

app.Run();
